// app.js
var config = require('/utils/config.js')
const socket = require('./utils/socketTast.js')
const api = require('/utils/api.js')
App({
	onLaunch() {
		// 获取状态栏高度
		// socket.socket.init();
		// webSocket开始启用
		// wx.getLocation({
		// 	type: 'wgs84',
		// 	success: function(res) {
		// 		console.log('获取经纬度成功', res)
		// 	},
		// 	fail: function(res) {
		// 		console.log('获取经纬度地址失败', res)
		// 	}
		// })
		var that = this;
		api.api.init();
		var inter = setInterval(function() {
			if (wx.getStorageSync('token')) {
				clearInterval(inter)
				socket.socket.createWebSocket()
			}
		}, 1000)
		wx.setStorageSync('config', config)
	},
	changeData: function() {
		var that = this
		that.onLoad();
	},
	onShow() {
		var that = this;
		that.globalData.userAllInfo = wx.getStorageSync('userAllInfo')

		var index = false;
		var intval = setInterval(function() {
			if (!index) {
				index = true
			}
		}, 5000)
		wx.authorize({
			scope: 'scope.userLocationBackground',
			success: function(res) {
				wx.startLocationUpdateBackground({
					type: 'gcj02',
					success: function() {
						if (that.globalData.userAllInfo !== null && that
							.globalData.userAllInfo
							.id !== undefined && that.globalData.userAllInfo
							.bank !== undefined) {
							wx.onLocationChange(function(res) {
								// console.log('位置移动', res)
								if (index) {
									index = false;
									socket.socket.socketTask.send({
										data: JSON.stringify({
											event: "pingAddress",
											data: {
												id: that
													.globalData
													.userAllInfo
													.id,
												address: res
													.longitude +
													',' +
													res
													.latitude
											}
										}),
										success: function(res) {
											// console.log(res)
										}
									})
								}

							})
						}
					},
					fail: function(res) {
						// console.log('未授权', res)
						wx.openSetting({})
					}
				})
			},
			fail: function(eor) {
				// console.log('授权失败', eor)
			}
		})
		// console.log('dfsadfs', socket.socket.onSocketMessageCallback)
		socket.socket.onSocketMessageCallback = function(res) {
			try {
				res = JSON.parse(res)
			} catch (e) {
				res = {
					event: "not",
					data: {}
				}
			}
			let event = res.event;
			var dataSkt = res.data;

			switch (event) {
				case "closeLink":
					socket.socket.close(false);
					return true;
					break;
				case "linkId":
					//链接绑定用户
					var intval = setInterval(function() {
						if (that.globalData.userAllInfo !== null && that.globalData.userAllInfo
							.id !== undefined && that.globalData.userAllInfo.bank !== undefined) {
							socket.socket.linkid = dataSkt;
							that.sendMessage('bindUser', {
								id: that.globalData.userAllInfo.id,
								portapp: 'djuser',
								bank: that.globalData.userAllInfo.bank
							})
							clearInterval(intval)
						}
					}, 1000)
					return true;
					break;
				case "resUser":
					//刷新用户
					for (var i in dataSkt) {
						that.data.userAllInfo[i] = dataSkt[i];
					}
					return true;
					break;
				case "user_wallet_change":
					//监听钱包变化
					let userdata = wx.getStorageSync('userAllInfo');
					for (var i in userdata.wallet) {
						if (Number(userdata.wallet[i].type) === Number(dataSkt.type)) {
							userdata.wallet[i] = dataSkt;
						}
					}
					wx.setStorageSync('userAllInfo', userdata)
					break;
			}
			that.messageEvent(event, dataSkt);
		}
		that.globalData.socket = socket.socket;
		that.globalData.socket.sendMessage = socket.sendSocketMsg;
	},
	messageEvent(event, data) {
		// console.log('socket消息')
	},
	/**
	 * 多图上传
	 * @param array data    需要上传的图片资源
	 * @param function callback   //每张图上传后的回调
	 * @param function step     //监听每张图上传的进度回调
	 * @param function endupload  //最终完成回调
	 * @param Number index    //初始上传的图片，会忽略掉 data 参数中index 之前的资源
	 * @param Number successData  //成功上传数
	 * @param Number errorData    //上传失败数
	 */
	uploadCommonImgAdmin(data, callback, step, endupload, index, successData, errorData) {
		if (index === undefined) index = 0;
		if (successData === undefined) successData = 0;
		if (errorData === undefined) errorData = 0;
		if (data[index] === undefined) {
			return true;
		}
		var that = this;
		var apis = api.api;
		var cursuccess = true;
		var requestdata = {
			strtotime: Date.parse(new Date())
		};
		var header = {
			'hj': 'lite',
			'portapp': 'djuser',
			'content-type': 'application/json',
			'bank': apis.getbank(),
			'auth': wx.getStorageSync('token') // 默认值
		};
		requestdata.sign = apis.autosign(requestdata);
		var uploadTask = wx.uploadFile({
			url: apis.host + "sys/uoloadFrom",
			filePath: data[index], //上传当前图片
			name: 'pic',
			header: header,
			formData: requestdata,
			success(res) {
				//上传完当前图片
				successData++;
				cursuccess = true;
				if (typeof callback === 'function') {
					if (Number(res.statusCode) === 200) {
						try {
							res.data = JSON.parse(res.data);
						} catch (e) {}
						callback(res.data, index, cursuccess, uploadTask);
					} else {
						callback(res, index, cursuccess, uploadTask);
					}
				}

			},
			fail(eor) {
				errorData++;
				cursuccess = false;
				if (typeof callback === 'function') {
					callback(eor, index, cursuccess, uploadTask);
				}
			},
			complete(res) {
				//上传完成
				if (Number(index) === data.length - 1) {
					if (typeof endupload === 'function') endupload(successData, errorData, data,
						uploadTask); //执行最终完成的回调
					return true; //执行进行下一次上传
				}
				index++; //指针指到下一个元素
				//上传未全部完成
				that.uploadCommonImgAdmin(data, callback, step, endupload, index, successData,
					errorData);
			}
		})
		//监听上传进度变化
		if (uploadTask) {
			uploadTask.onProgressUpdate(function(data) {
				if (typeof step === 'function') step(data, index, uploadTask)
			});
		}
	},
	/**
	 * 公共上传图片
	 * @param number number  上传数量 默认 1
	 * @param function callback 上传完成的回调函数 
	 * @param function step 上传进度条的回调函数
	 */
	uploadCommonImg(number, callback, beforeback, endback, step) {
		var that = this;
		var apis = api.api;
		if (number === undefined) number = 1;
		wx.chooseImage({
			count: Number(number),
			success(res) {
				console.log('sdf', res)
				if (typeof beforeback === 'function') {
					beforeback(res.tempFilePaths);
				}
				//循环上传对象
				that.uploadCommonImgAdmin(res.tempFilePaths, callback, step, endback);
			},
			fail(eor) {
				wx.showToast({
					title: '打开本地图片失败',
					icon: "error"
				})
			}
		})
	},
	sendMessage(event, data) {
		this.globalData.socket.sendMessage({
			data: {
				event: event,
				data: data
			},
			success(res) {
				// console.log("发送信息成功", event)
			},
			fail(error) {
				// console.log('消息发送失败', error)
			}
		});
	},
	setGetOrderData(userid) {
		wx.setStorageSync('scene_djId', userid)
		this.globalData.dj_id = userid;
	},
	getGetOrderData() {
		if (Number(this.globalData.dj_id) > 0) {
			return this.globalData.dj_id;
		} else {
			return 0;
		}
	},
	setSecene(data) {
		this.globalData.puser_id = data.user_id;
		try {
			if (typeof data.content == 'string') {
				this.globalData.secene_content = JSON.parse(data.content);
			} else {
				this.globalData.secene_content = data.content;
			}
		} catch (e) {
			//TODO handle the exception
			this.globalData.secene_content = {};
		}
		wx.setStorageSync('scene', {
			user_id: data.user_id,
			content: this.globalData.secene_content
		})
	},
	commonInit(res) {
		if (res.t === 'getorder') {
			//扫描接单二维码
			this.setGetOrderData(res.data.content.id);
			wx.showToast({
				title: "已指定接单代驾，请前往下单"
			})
			// wx.navigateTo({
			// 	url: "/pages/index/index"
			// })
		} else if (res.t == "traderorder") {
			wx.showToast({
				title: "已绑定商家，请前往下单"
			})
			this.setTrader(res.data);
			// wx.redirectTo({
			// 	url: '/pages/index/index'
			// })
		} else if (res.t && res.t.indexOf('usermore') === 0) {
			//推广码
			this.setSecene(res.data);
		}
	},
	getSecene() {
		if (Number(this.globalData.puser_id) > 0) {
			return {
				puser: this.globalData.puser_id,
				content: this.globalData.secene_content
			}
		} else {
			return {}
		}
	},
	getTraderId() {
		return this.globalData.trader.content ? (this.globalData.trader.content ? this.globalData.trader.content
			.trader : 0) : 0;
	},
	setTrader(data) {
		this.globalData.trader = data;
	},
	getScene(scene, callBack) {
		//获取onLoad内的options.scene内容
		// https://dageda.api.hjdz.ltd/index/getScene
		var that = this;
		var apis = api.api;
		var url = apis.host + 'dis/getScene';
		var data = {
			scene: scene,
		}
		apis.request(url, data, 'POST').then(function(res) {
			if (res.code == 200) {
				that.initSecene(res.data);
				if (typeof callBack == 'function') {
					res.data.content = JSON.parse(res.data.content);
					callBack(res.data)
				}
			}
		})
	},
	getYwId() {
		let secene = this.getSecene();
		// console.log('dadfasdfsdfasd', secene)
		if (secene.puser === undefined) {
			return -1;
		}
		if (secene.content.type === 'usermore12') {
			return secene.puser;
		} else {
			return -1;
		}
	},
	getRecommon() {
		let secene = this.getSecene();
		if (secene.puser === undefined) {
			return '';
		}
		return secene.content.recomment;
	},
	getRecommonType() {
		let secene = this.getSecene();
		if (secene.puser === undefined) {
			return '0';
		}
		return secene.content.type;
	},
	initSecene(data) {
		if (data.path !== "" && data.path != 'pages/index/index') {
			wx.redirectTo({
				url: '/' + data.path
			})
		}

	},
	initUser() {
		let apis = api.api;
		let url = apis.host + 'user/getuser';
		let data = {};
		var that = this;
		if (wx.getStorageSync('token')) {
			apis.request(url, data, 'POST').then(function(res) {
				if (res.code == 200) {
					apis.setUserInfo(res.data)
					that.globalData.userAllInfo = res.data;
				}
			})
		}
	},
	commonScan(callback) {
		var that = this;
		wx.scanCode({
			success(res) {
				var data;
				try {
					data = JSON.parse(res.result);
				} catch (e) {
					//TODO handle the exception
					data = {};
				}
				if (res.scanType == "WX_CODE") {
					//如果res.scanType == "WX_CODE", 则为小程序
					var resPath = res.path.split("=")
					if (resPath[1] != undefined) {
						that.getScene(resPath[1], function(res) {
							if (typeof callback === 'function') {
								try {
									if (typeof res.content === 'string') {
										res.content = JSON.parse(res.content);
									}
								} catch (e) {
									//TODO handle the exception
									res.content = {}
								}
								let arr = res.url.split('/');
								let typemore = arr[arr.length - 1];
								let typearr = typemore.split('.');
								let type = typearr[0];
								callback({
									t: type,
									data: res
								});
							}
						})
					}
				} else {
					if (typeof callback === 'function') {
						callback(data);
					}
				}
			}
		})
	},
	getUserInfo(user_id, callback) {
		var userinfo = wx.getStorageSync('userInfo_' + user_id);
		if (userinfo) {
			if (typeof callback === 'function') {
				callback(userinfo);
			}
		} else {
			let apis = api.api;
			let url = apis.host + 'sys/userinfo'
			let data = {
				id: user_id
			}
			apis.request(url, data, 'POST').then(function(res) {
				if (res.code == 200) {
					wx.setStorageSync('userInfo_' + user_id, res.data)
					if (typeof callback === 'function') {
						callback(res.data);
					}
				} else {
					if (typeof callback === 'function') {
						callback(false);
					}
				}
			}, function(res) {
				// if (res.code == failed) {

				// }
			})
		}
	},
	//退出登录
	logout() {
		// 清理本地缓存
		wx.clearStorage()
		// 断开socket连接
		socket.socket.close()
		wx.navigateTo({
			url: '/pages/login/login'
		})
	},
	globalData: {
		userInfo: null,
		code: '',
		navHeight: 0,
		timeId: '',
		isLogin: null,
		customBar: null,
		userAllInfo: null,
		token: '',
		phone: '', // 标识用户是否已绑定手机号码
		origin: '', // 出发地的地址
		host: 'https://cdn.oss.dgddaijia.com',
		socket: null,
		puser_id: 0,
		wallet: [],
		secene_content: {},
		trader: {}
	},
})
